<template>
  <div
    v-loading="loading"
    v-empty="!productReadAuth"
    xs-empty-icon="nopermission"
    xs-empty-text="暂无权限"
    class="detail-tab">
    <template v-if="productReadAuth && showTable">
      <flexbox
        align="center"
        justify="flex-end"
        class="control-btn">
        <el-button
          v-if="selectedList.length > 0"
          type="primary"
          size="mini"
          class="xr-btn--orange"
          @click="handleRemoveRelative">
          解除关联
        </el-button>
        <el-button
          type="primary"
          size="mini"
          class="xr-btn--orange"
          @click="handleRelativeAll">
          关联所有产品
        </el-button>
        <el-popover
          v-model="showPopover"
          :disabled="!tableOk"
          placement="right-start"
          width="700"
          popper-class="no-padding-popover"
          trigger="click">

          <relative-card
            v-model="showPopover"
            :request-config="requestConfig"
            primary-key="productId"
            label="关联供货产品"
            @close="showPopover = !showPopover"
            @confirm="handleRelativeConfirm">
            <el-button
              slot="header-right"
              type="primary"
              class="new-button xr-btn--primary"
              @click.stop="handleAddProduct">
              新建
            </el-button>
          </relative-card>

          <el-button
            slot="reference"
            type="primary"
            size="mini"
            icon="el-icon-plus"
            class="xr-btn--orange">
            关联供货产品
          </el-button>
        </el-popover>
      </flexbox>

      <tab-table
        :request-config="tabTableReqConfig"
        class="table-list"
        @render-ok="handleTableOk"
        @selection-change="handleSelectionChange"
        @row-click="handleTableRowClick">
        <el-table-column
          slot="left"
          type="selection"
          align="center"
          width="55" />
      </tab-table>
    </template>

    <j-x-c-full-screen-detail
      v-if="showDetail && rowId && detailType"
      :id="rowId"
      :type="detailType"
      @update="handleRefresh"
      @close="showDetail = false" />

    <create-com
      v-if="showAddProduct"
      type="jxc_product"
      @update="handleRefresh"
      @close="showAddProduct = false" />
  </div>
</template>

<script>
import {
  jxcFieldQueryPageListAPI,
  jxcFieldDetailOtherFieldListAPI,
  jxcFieldQueryListAPI
} from '@/api/jxc/field'
import {
  jxcSupplierRelatedProductsAPI,
  jxcSupplierRelatedAllProductsAPI,
  jxcSupplierUnRelatedProductsAPI
} from '@/api/jxc/supplier'

import TabTable from '../../../components/DetailTab/TabTable'
import RelativeCard from '../../../components/RelativeCard'
import CreateCom from '../../../components/Create/CreateCom'

import JxcTypes from '../../../jxcTypes'
import { mapGetters } from 'vuex'

// 产品
export default {
  name: 'TabProductList',
  components: {
    TabTable,
    RelativeCard,
    CreateCom,
    JXCFullScreenDetail: () => import('../../../components/JXCFullScreenDetail')
  },
  inheritAttrs: false,
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      loading: false,
      showTable: false,
      showFreeRelative: false,

      // 供应商下产品
      tabTableReqConfig: {
        fieldParams: {
          label: JxcTypes.jxc_product.label,
          otherLable: 1
        },
        fieldRequest: jxcFieldDetailOtherFieldListAPI,
        listParams: {
          label: JxcTypes.jxc_product.label,
          searchList: []
        },
        listRequest: jxcFieldQueryListAPI,
        canVisitField: ['productName']
      },

      // 供应商关联产品
      requestConfig: {
        fieldRequest: jxcFieldDetailOtherFieldListAPI,
        fieldParams: {
          label: JxcTypes.jxc_product.label,
          otherLable: JxcTypes.jxc_supplier.label
        },
        listRequest: jxcFieldQueryPageListAPI,
        listParams: {
          label: JxcTypes.jxc_product.label,
          searchList: [
            {
              name: 'product_id',
              formType: 'text',
              type: 14,
              values: []
            }
            // {
            //   formType: 'text',
            //   type: 1,
            //   name: 'product_ishelf', // 上架的产品
            //   values: [1]
            // }
          ]
        }
      },
      showPopover: false,

      tableOk: false,
      tabTableList: [],
      selectedList: [],

      rowId: '',
      detailType: '',
      showDetail: false,

      showAddProduct: false
    }
  },
  computed: {
    ...mapGetters(['jxc']),
    productReadAuth() {
      return this.jxc && this.jxc.product && this.jxc.product.read
    }
  },
  watch: {
    id: {
      handler(val) {
        this.showTable = false
        this.tabTableReqConfig.listParams.searchList = [{
          name: 'supplier_id',
          formType: 'text',
          type: 15,
          values: [this.id]
        }]
        this.tableOk = false
        this.$nextTick(() => {
          this.showTable = true
        })
      },
      immediate: true
    },
    tabTableList: {
      handler(val) {
        if (this.tableOk && val) {
          console.log('data: ----', val)
          this.requestConfig.listParams.searchList[0].values = val.map(o => o.productId)
        }
      },
      deep: true
    }
  },
  created() {
    this.requestConfig.searchParamsFn = this.searchParamsFn
  },
  methods: {
    /**
     * 拼接搜索参数
     * @param params
     * @param keyword
     */
    searchParamsFn(params, keyword) {
      if (keyword) {
        params.searchList.push({
          name: 'product_name',
          formType: 'text',
          type: 3,
          values: [keyword]
        })
      }
      return params
    },

    handleAdd() {
      this.showFreeRelative = !this.showFreeRelative
    },

    handleAddProduct() {
      this.showPopover = false
      this.showAddProduct = true
    },

    handleTableOk(data) {
      this.tableOk = true
      this.tabTableList = data.data || []
    },

    /**
     * 刷新
     */
    handleRefresh() {
      this.selectedList = []
      this.showTable = false
      this.$nextTick(() => {
        this.showTable = true
      })
    },

    handleSelectionChange(data) {
      this.selectedList = data
      console.log('selectedList', this.selectedList)
    },

    handleTableRowClick(row, field) {
      this.detailType = 'jxc_product'
      this.rowId = row.productId
      this.showDetail = true
    },

    /**
     * 一键关联全部
     */
    handleRelativeAll() {
      this.$confirm('您确定要一键关联所有产品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        jxcSupplierRelatedAllProductsAPI({
          id: this.id
        }).then(() => {
          this.loading = false
          this.$message.success('操作成功')
          this.handleRefresh()
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
        this.$message.info('已取消')
      })
    },

    /**
     * 解除关联
     */
    handleRemoveRelative() {
      if (this.selectedList.length === 0) return
      this.$confirm('您确定要把这些产品解除关联吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        jxcSupplierUnRelatedProductsAPI({
          productIds: this.selectedList.map(o => o.productId).join(','),
          supplierId: this.id
        }).then(() => {
          this.loading = false
          this.$message.success('操作成功')
          this.handleRefresh()
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
        this.$message.info('已取消')
      })
    },

    handleRelativeConfirm(data) {
      if (data.data.length > 0) {
        jxcSupplierRelatedProductsAPI({
          supplierId: this.id,
          productIds: data.valData.join(',')
        }).then(() => {
          this.$message.success('操作成功')
          this.showPopover = false
          this.showTable = false
          this.$nextTick(() => {
            this.showTable = true
          })
        }).catch(() => {})
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import "../../../styles/detailTab";

.detail-tab {
  .control-btn {
    margin-bottom: 10px;
    .el-button {
      margin-left: 10px;
    }
  }

  .new-button {
    height: 34px;
    line-height: 34px;
  }
}
</style>
